package com.apps.ftapp.fragment;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.apps.ftapp.R;
import com.apps.ftapp.act.FenXiangZhuanQianActivity;
import com.apps.ftapp.act.ShouYiActivity;
import com.apps.ftapp.activity.LogisticsActivity;
import com.apps.ftapp.activity.MyErrorSubjectActivity;
import com.apps.ftapp.activity.MyLessonActivity;
import com.apps.ftapp.activity.MyLessonCacheActivity;
import com.apps.ftapp.activity.MyLessonCacheJyActivity;
import com.apps.ftapp.activity.MyOrderActivity;
import com.apps.ftapp.activity.MySubjectCollActivity;
import com.apps.ftapp.activity.MySubjectKeepActivity;
import com.apps.ftapp.activity.NoticeActivity;
import com.apps.ftapp.activity.StatisticsActivity;
import com.apps.ftapp.activity.UserInfoActivity;
import com.apps.ftapp.bean.ShareModel;
import com.apps.ftapp.db.Kj;
import com.apps.ftapp.db.Lesson;
import com.apps.ftapp.db.LessonChild;
import com.apps.ftapp.model.CommModel;
import com.apps.ftapp.model.UserInfoModel;
import com.apps.ftapp.util.ActivitySkipUtil;
import com.apps.ftapp.util.Async;
import com.apps.ftapp.util.Constant;
import com.apps.ftapp.util.L;
import com.apps.ftapp.util.SDCardUtils;
import com.apps.ftapp.util.Tools;
import com.duobeiyun.util.FileUtil;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import org.litepal.crud.DataSupport;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cz.msebera.android.httpclient.Header;
import de.hdodenhof.circleimageview.CircleImageView;
import es.dmoral.toasty.Toasty;
import me.leefeng.promptlibrary.PromptDialog;

/**
 * A simple {@link Fragment} subclass.
 * 我的 fragment
 */
public class AccountFragment extends Fragment implements View.OnClickListener {


    @BindView(R.id.edit_user_info)
    Button editUserInfo;
    @BindView(R.id.user_icon)
    CircleImageView userIcon;
    @BindView(R.id.nickname)
    TextView nickname;
    @BindView(R.id.user_sign)
    TextView userSign;
    @BindView(R.id.my_error_subject)
    Button myErrorSubject;
    @BindView(R.id.my_subject_jl)
    Button mySubjectJl;
    @BindView(R.id.my_subject_collect)
    Button mySubjectCollect;
    @BindView(R.id.textView2)
    TextView textView2;
    @BindView(R.id.wodekecheng)
    RelativeLayout wodekecheng;
    @BindView(R.id.huancunkecheng)
    RelativeLayout huancunkecheng;
    @BindView(R.id.huancunjiangyi)
    RelativeLayout huancunjiangyi;
    @BindView(R.id.youhuiquan)
    RelativeLayout youhuiquan;
    @BindView(R.id.wodedingdan)
    Button wodedingdan;
    @BindView(R.id.xiaoxi)
    Button xiaoxi;
    @BindView(R.id.lianxikefu)
    Button lianxikefu;
    @BindView(R.id.notice_num)
    TextView num;

    @BindView(R.id.shezhi)
    Button shezhi;
    @BindView(R.id.tuijian)
    Button tuijian;
    Unbinder unbinder;
    @BindView(R.id.wuliuxinxi)
    Button wuliuxinxi;
    @BindView(R.id.fenxiangzhuanqian)
    Button fenxiangzhuanqian;
    @BindView(R.id.wodeshouyi)
    Button wodeshouyi;
    @BindView(R.id.tongji)
    Button tongji;


    private ImageLoader imageLoader = ImageLoader.getInstance();
    private DisplayImageOptions options;

    private Gson gson = new Gson();

    public AccountFragment() {
        // Required empty public constructor
    }

    private PromptDialog promptDialog;
    private String dirName = SDCardUtils.getSDCardPath() + "duobeiyun/";


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_account, container, false);
        unbinder = ButterKnife.bind(this, view);
        ShareSDK.initSDK(getContext());

        //显示图片的配置
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.mipmap.ic_launcher)
                .showImageOnFail(R.mipmap.ic_launcher).cacheInMemory(true).cacheOnDisk(true).bitmapConfig(Bitmap.Config.RGB_565).build();
        imageLoader.init(ImageLoaderConfiguration.createDefault(getContext()));
        myErrorSubject.setOnClickListener(this);
        editUserInfo.setOnClickListener(this);
        mySubjectJl.setOnClickListener(this);
        mySubjectCollect.setOnClickListener(this);
        wodekecheng.setOnClickListener(this);
        huancunjiangyi.setOnClickListener(this);
        huancunkecheng.setOnClickListener(this);
        wodedingdan.setOnClickListener(this);
        xiaoxi.setOnClickListener(this);
        shezhi.setOnClickListener(this);
        youhuiquan.setOnClickListener(this);
        lianxikefu.setOnClickListener(this);
        userIcon.setOnClickListener(this);
        wuliuxinxi.setOnClickListener(this);
        tuijian.setOnClickListener(this);
        fenxiangzhuanqian.setOnClickListener(this);
        wodeshouyi.setOnClickListener(this);
        tongji.setOnClickListener(this);
        loadData();

        return view;
    }

    private void loadData() {

        RequestParams params = new RequestParams();
        params.put("token", Constant.token);
        params.put("userId", Constant.uid);
        Async.post("settings/", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    L.i("main", "-------" + new String(responseBody));

                    UserInfoModel result = gson.fromJson(new String(responseBody), UserInfoModel.class);
                    if (1 == Tools.isIntNull(result.getSuccess())) {

                        imageLoader.displayImage(result.getData().getLargeAvatar(), userIcon, options);
                        nickname.setText(result.getData().getNickname());
                        try {
                            userSign.setText(result.getData().getCategory().get(1));
                        } catch (Exception e) {
                            userSign.setText("");
                        }
                    }

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }

            @Override
            public void onFinish() {
                super.onFinish();
                getnoticeNum();
            }
        });


    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {

            case R.id.user_icon:

                ActivitySkipUtil.skipAnotherActivity(getActivity(), UserInfoActivity.class, false);
                break;
            case R.id.edit_user_info:
                //编辑资料
                ActivitySkipUtil.skipAnotherActivity(getActivity(), UserInfoActivity.class, false);

                break;

            case R.id.my_error_subject:
                //我的错题
                ActivitySkipUtil.skipAnotherActivity(getActivity(), MyErrorSubjectActivity.class, false);
                break;

            case R.id.my_subject_jl:
                //做题记录
                ActivitySkipUtil.skipAnotherActivity(getActivity(), MySubjectKeepActivity.class, false);
                break;

            case R.id.my_subject_collect:
                //题目收藏
                ActivitySkipUtil.skipAnotherActivity(getActivity(), MySubjectCollActivity.class, false);
                break;

            case R.id.wodekecheng:
                //我的课程
                ActivitySkipUtil.skipAnotherActivity(getActivity(), MyLessonActivity.class, false);
                break;
            case R.id.huancunkecheng:
                //缓存课程
                ActivitySkipUtil.skipAnotherActivity(getActivity(), MyLessonCacheActivity.class, false);
                break;

            case R.id.huancunjiangyi:
                //缓存讲义
                ActivitySkipUtil.skipAnotherActivity(getActivity(), MyLessonCacheJyActivity.class, false);
                break;

            case R.id.wodedingdan:
                //我的订单
                ActivitySkipUtil.skipAnotherActivity(getActivity(), MyOrderActivity.class, false);
                break;

            case R.id.xiaoxi:
                //我的消息
                ActivitySkipUtil.skipAnotherActivity(getActivity(), NoticeActivity.class, false);
                break;
            case R.id.youhuiquan:
                //我的优惠券
                ActivitySkipUtil.skipAnotherActivity(getActivity(), NoticeActivity.class, false);
                break;


            case R.id.lianxikefu:
                //联系客服
//                bohao();
                call("18179185700");
//                ActivitySkipUtil.skipAnotherActivity(getActivity(), MyLessonActivity.class,false);
                break;


            case R.id.shezhi:
                new MaterialDialog.Builder(getActivity())
                        .title(R.string.title1)
                        .content(R.string.clear_cache)
                        .contentColor(Color.BLACK)
                        .positiveText(R.string.agree)
                        .positiveColor(Color.BLACK)
                        .negativeColor(Color.BLACK)
                        .negativeText(R.string.disagree)
                        .onAny(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                if (which == DialogAction.NEUTRAL) {
                                } else if (which == DialogAction.POSITIVE) {
                                    //清理
                                    promptDialog = new PromptDialog(getActivity());
                                    promptDialog.showLoading("清理中..");
                                    FileUtil.deleteFile(dirName);
                                    //删除数据库数据
                                    DataSupport.deleteAll(LessonChild.class);
                                    DataSupport.deleteAll(Lesson.class);
                                    DataSupport.deleteAll(Kj.class);
                                    //删除数据库数据
                                    promptDialog.dismiss();

                                    //filesize.setText("0.0M");

                                    Toasty.normal(getActivity().getApplicationContext(), "清理完成〜").show();
//                          Toast.makeText(MainActivity.this, "同意" + dataChoose, Toast.LENGTH_LONG).show();
                                } else if (which == DialogAction.NEGATIVE) {
                                }

                            }
                        })
                        .show();


                //设置
                //ActivitySkipUtil.skipAnotherActivity(getActivity(), SetActivity.class, false);
                break;

            case R.id.wuliuxinxi:
                //物流信息
                ActivitySkipUtil.skipAnotherActivity(getActivity(), LogisticsActivity.class, false);

                break;
            case R.id.tuijian:
                share();
                break;

            case R.id.fenxiangzhuanqian:
                //如何赚钱
                ActivitySkipUtil.skipAnotherActivity(getActivity(), FenXiangZhuanQianActivity.class, false);
                break;

            case R.id.wodeshouyi:
                //我的收入
                ActivitySkipUtil.skipAnotherActivity(getActivity(), ShouYiActivity.class, false);

                break;

            case R.id.tongji:
                ActivitySkipUtil.skipAnotherActivity(getActivity(), StatisticsActivity.class, false);

                break;
        }
    }

    private void share() {

        RequestParams params = new RequestParams();
        params.put("token", Constant.token);
        params.put("userId", Constant.uid);
        Async.post("share", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    L.i("main", "-------" + new String(responseBody));
                    ShareModel result = gson.fromJson(new String(responseBody), ShareModel.class);
                    if (1 == Tools.isIntNull(result.getSuccess())) {
                        shareSdk(result);
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });
    }

    private void getnoticeNum() {
        RequestParams params = new RequestParams();
        params.put("token", Constant.token);
        params.put("userId", Constant.uid);
        Async.post("readnew", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                CommModel commModel = gson.fromJson(new String(responseBody), CommModel.class);
                if (commModel.getSuccess() == 1) {
                    if (commModel.getNewnum() > 0) {
                        num.setText(String.valueOf(commModel.getNewnum()));
                        num.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        num.setVisibility(View.GONE);
        loadData();
    }

    private void shareSdk(ShareModel result) {
        ShareModel.SharesBean shareBean = result.getShares();
        if (null != shareBean) {
            OnekeyShare oks = new OnekeyShare();
            oks.disableSSOWhenAuthorize();
            oks.setTitle(shareBean.getTitle());
            oks.setTitleUrl(shareBean.getUrl());
            oks.setText(shareBean.getTitle());
            oks.setImageUrl(shareBean.getImage());
            oks.setUrl(shareBean.getUrl());
            oks.setSite(shareBean.getTitle());
            oks.setSiteUrl(shareBean.getUrl());
            oks.show(getActivity());
        }
    }


    /**
     * 调用拨号功能
     *
     * @param phone 电话号码
     */
    private void call(String phone) {
        L.i("main", "-------");
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }
}
